<?php

namespace App\Common\Util;

use App\Common\Exception\ApiMessageException;
use Sc\Util\Tool\JWT;

/**
 * Class ApiAuth
 */
class ApiAuth
{
    private static $TOKEN = null;

    /**
     * 获取token值
     *
     * @param string|null $key
     * @param mixed|null  $default
     *
     * @return mixed|null
     */
    public static function get(string $key = null, mixed $default = null): mixed
    {
        if ($key === null) {
            return self::$TOKEN;
        }

        return self::$TOKEN[$key] ?? $default;
    }

    /**
     * 设置token值
     *
     * @param string|array $key
     * @param mixed|null   $value
     *
     * @return void
     */
    public static function set(string|array $key, mixed $value = null): void
    {
        self::$TOKEN = is_array($key) ? $key : [$key => $value];
    }

    /**
     * 验证
     *
     * @return void
     * @throws ApiMessageException
     */
    public static function verify(): void
    {
        if (!self::$TOKEN) {
            throw new ApiMessageException("Token error", JWT::ERROR_CODE);
        }

        if ((isset(self::$TOKEN['exp']) && self::$TOKEN['exp'] < time()) || (isset(self::$TOKEN['nbf']) && self::$TOKEN['nbf'] > time())) {
            throw new ApiMessageException("Token expire", JWT::EXPIRE_CODE);
        }
    }
}
